import { Button } from 'antd-mobile'
import styles from '../css/ticket-order.module.css'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { useSelector } from 'react-redux'
import { useEffect, useMemo, useState } from 'react'
import eventBus from '../../../utils/eventBus'
import { createOrderApi } from '../../../api/ticket'

function Footer(props) {
  const [sp] = useSearchParams()
  const len = useSelector((store) => store.order.passengers.length)
  const passengers = useSelector((store) => store.order.passengers)
  const [seats, setSeats] = useState([])
  const nav = useNavigate()

  useEffect(() => {
    const fn = (val) => {
      console.log('在 Footer 组件中，接收到了兄弟组件发送来的座位数据：')
      console.log(val)
      setSeats(val)
    }
    // 只在组件首次创建的时候，监听一个名为 share 的自定义事件
    eventBus.on('share', fn)

    // 在清理函数中，解绑事件
    return () => eventBus.off('share', fn)
  }, [])

  const amount = useMemo(() => {
    return Number(sp.get('price')) * len
  }, [sp, len])

  // 点击提交订单按钮，调用接口下单，再跳转到订单详情页
  const createOrder = async () => {
    // 1. 封装接口
    // 2. 准备接口需要用到的数据对象
    const data = {
      train_id: props.id,
      start: props.startStation,
      end: props.endStation,
      date: sp.get('date'),
      seatType: sp.get('seat'),
      seats,
      passengers
    }

    const { data: res } = await createOrderApi(data)
    console.log(res)
    // 3. 调用接口下单
    // 4. 下单完成后，通过路由导航，跳转到订单详情页面，
    // 5. 同时把下单后返回的订单信息，通过路由的 state 传入到订单详情页
    nav('/get-order', {
      state: res
    })
  }

  return (
    <div className={styles.footer}>
      <div>
        <span className={styles.price}>￥{amount}</span>
        <span className={styles.tip}>支付金额</span>
      </div>
      <Button
        color="primary"
        onClick={createOrder}
      >
        提交订单
      </Button>
    </div>
  )
}

export default Footer
